package gitapp.oschina.net.my_osc;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @author Tristan-Hou
 *
 */
public class AppConfig {

    private final static String APP_CONFIG = "config";

    public final static String CONF_APP_UNIQUEID = "APP_UNIQUEID";

    public final static String CONF_LOAD_IMAGE = "perf_loadimage";

    public final static String CONF_HTTPS_LOGIN = "perf_httpslogin";

    public final static String CONF_RECEIVENOTICE = "perf_receivenotice";

    public final static String CONF_VOICE = "perf_voice";

    public final static String CONF_CHECKUP = "perf_checkup";

    public final static String CONF_FRIST_START = "isFristStart";

    private Context mContext;
    private static AppConfig appConfig;
    public static AppConfig getAppConfig(Context context){
        if (appConfig == null){
            appConfig = new AppConfig();
            appConfig.mContext = context;
        }
        return appConfig;
    }

    public void set(String key, String value){
        Properties props = get();
        props.setProperty(key, value);
        setProps(props);
    }

    public String get(String key){
        Properties props = get();
        return (props != null)?props.getProperty(key):null;
    }

    private void setProps(Properties props){
        FileOutputStream fos = null;
        File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
        try {
            fos = new FileOutputStream(new File(dirConf, APP_CONFIG));
            props.store(fos, null);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Properties get() {
        FileInputStream fis = null;
        Properties props = new Properties();
        try {
            File dirConf = mContext.getDir(APP_CONFIG, Context.MODE_PRIVATE);
            fis = new FileInputStream(dirConf.getPath() + File.separator
                    + APP_CONFIG);

            props.load(fis);
        } catch (Exception e) {
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return props;
    }
}
